//
//  NvWindowPlayer.m
//  NvSellerShow
//
//  Created by bmd on 2017/3/27.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvWindowPlayer.h"
#import "NvMakeFilmClipModel.h"
#import "NvsVideoTrack.h"
#import "NvsVideoClip.h"
#import "NvsAudioTrack.h"
#import "NvAssetModel.h"
#import "NvPlaySlider.h"

@interface NvWindowPlayer ()<NvsStreamingContextDelegate> {
    NSTimer *timer,*bottomTimer;
    __weak UIView *_superView;
    CGRect _rect;
    BOOL isPlaying;
    BOOL _isFull;
    UIWindowLevel windowLevel;
    int64_t triminTimeStamp,trimoutTimeStamp;
    BOOL _needClearTimeLine;
    BOOL haveFullButton;
}

@property (weak, nonatomic) IBOutlet NvsLiveWindow *liveWindow;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
- (IBAction)playButtonClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet NvPlaySlider *slider;
- (IBAction)valueChange:(id)sender;
- (IBAction)fullButtonClick:(id)sender;
@property (weak, nonatomic) IBOutlet UIView *playerBottomView;
@property (weak, nonatomic) IBOutlet UIButton *play_pause;


@end

@implementation NvWindowPlayer

+ (instancetype) instancePlayer {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    return [[myBundle loadNibNamed:@"NvWindowPlayer" owner:self options:nil] firstObject];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    self = [[myBundle loadNibNamed:@"NvWindowPlayer" owner:self options:nil] firstObject];
    self.frame = frame;
    return self;
}


- (void)awakeFromNib {
    [super awakeFromNib];
    self.clipsToBounds = YES;

    haveFullButton = YES;
    self.playStart = 0;
    self.playEnd = 0;
    self.slider.value = 0;
    _needClearTimeLine = NO;
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    windowLevel = window.windowLevel;
    isPlaying = NO;
    _isFull = NO;
    [self addTapGestureRecognizer];
}

//before this can set self timeline
- (void)connectTimelineAndLiveWindow {
    [self createStreamingContext];
    [self createTimeLine];
    
    [self.streamingContext connectTimeline:self.timeline withLiveWindow:self.liveWindow];
    self.streamingContext.delegate = self;
    
    if(self.playEnd == 0) {
        self.playStart = 0;
        self.playEnd = self.timeline.duration;

    }
    [self updateTotalLabel];
    [self pause];
    [self.streamingContext seekTimeline:self.timeline timestamp:self.playStart videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
}

- (void)updateTotalLabel {
    int64_t duration = self.playEnd - self.playStart;
    self.totalTimeLabel.text = [Utils stringWithTime:1.0*duration / NS_TIME_BASE];
}

- (void)startTimer {
    bottomTimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(timerClick) userInfo:nil repeats:NO];
}

- (void)timerClick {
    if (self.playerBottomView.bottom_LL == self.liveWindow.bottom_LL) {
        //隐藏
        [self hidenBottonView];
    }
}

- (void)addTapGestureRecognizer {
    [self addTapGestureRecognizer:@selector(tapGestureRecognizer) target:self];
}
- (void)tapGestureRecognizer {
    if (self.playerBottomView.bottom_LL == self.liveWindow.bottom_LL) {
        //隐藏
        [self hidenBottonView];
    } else {
        //显示
        [self showBottomView];
    }
}

//隐藏控制栏
- (void)hidenBottonView {
    [bottomTimer invalidate];
    [UIView animateWithDuration:0.3 animations:^{
        self.playerBottomView.top_LL = self.liveWindow.bottom_LL;
    }];
}
//显示控制栏
- (void)showBottomView {
    [UIView animateWithDuration:0.3 animations:^{
        self.playerBottomView.bottom_LL = self.liveWindow.bottom_LL;
    } completion:^(BOOL finished) {
        [self startTimer];
    }];
}
- (IBAction)playClick:(id)sender {
    [self play];
}

- (void)play {
    isPlaying = YES;
    self.play_pause.hidden = YES;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    [self.playButton setImage:[UIImage imageWithContentsOfFile:[myBundle pathForResource:@"player_stop" ofType:@"png"] ] forState:UIControlStateNormal];
    if (triminTimeStamp!=0||trimoutTimeStamp!=self.timeline.duration) {//视频是否经过裁剪
        int64_t currentTime = self.slider.value*self.timeline.duration;
        if (currentTime>trimoutTimeStamp||currentTime<triminTimeStamp) {//滑动条超出剪切的范围
            [self.streamingContext seekTimeline:self.timeline timestamp:triminTimeStamp videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
            [self.streamingContext playbackTimeline:self.timeline startTime:triminTimeStamp endTime:trimoutTimeStamp videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
        } else {//滑动条没有超出剪切范围
            [self.streamingContext playbackTimeline:self.timeline startTime:currentTime endTime:trimoutTimeStamp videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
        }
    } else {
        int64_t startTime = self.playStart + self.slider.value * (self.playEnd - self.playStart);
        [self.streamingContext playbackTimeline:self.timeline startTime:startTime endTime:self.playEnd videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
    }
    timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(handleSliderChange) userInfo:nil repeats:YES];
}

- (void)pause {
    isPlaying = NO;
    self.play_pause.hidden = NO;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    [self.playButton setImage:[UIImage imageWithContentsOfFile:[myBundle pathForResource:@"player_play" ofType:@"png"] ] forState:UIControlStateNormal];
    [self.streamingContext stop];
    [timer invalidate];
}

- (void)setSuperView:(UIView *)superView {
    if (superView!=nil) {
        _superView = superView;
        _rect = self.frame;
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.play_pause.center = self.liveWindow.center;
    self.playerBottomView.frame = CGRectMake(0, self.bounds.size.height-44, self.bounds.size.width, 44);
    if (self.createMode == NvSSVideoCreateScaleSquare) {
        self.liveWindow.frame = CGRectMake((self.bounds.size.width-self.bounds.size.height)/2, 0, self.bounds.size.height, self.bounds.size.height);
    }else if (self.createMode == NvSSVideoCreateScaleVertical) {
        self.liveWindow.frame = CGRectMake((self.bounds.size.width-self.bounds.size.height*9.0/16.0)/2, 0, self.bounds.size.height*9.0/16.0, self.bounds.size.height);
        
    }
}

- (void)createStreamingContext {
    
    if (!_streamingContext) {
        self.streamingContext =[NvsStreamingContext sharedInstanceWithFlags:NvsStreamingContextFlag_Support4KEdit];
    }
    
}
//创建时间线
- (void)createTimeLine {
    if (!_timeline) {
        self.timeline = [Utils createTimeLine:self.createMode];
        self.videoTrack = [self.timeline appendVideoTrack];
        _needClearTimeLine = YES;
    }
}

- (void)setTimeline:(NvsTimeline *)timeline {
    _timeline = timeline;
    triminTimeStamp = 0;
    trimoutTimeStamp = _timeline.duration;
}

//设置需要播放的数据
- (void)setModel:(MediaModel *)model {
    [self connectTimelineAndLiveWindow];
    if(model == nil)
        return;
    _model = model;
    if([self.timeline getCurrentThemeId]) {
        [self.timeline removeCurrentTheme];
    }
    if(self.timeline.videoTrackCount == 0) {
        [self.timeline appendVideoTrack];
    }
    NvsVideoTrack *videoTrack =  [self.timeline getVideoTrackByIndex:0];
    [videoTrack removeAllClips];
    NSArray *modelArray = model.modelArray;
    for(NvMakeFilmClipModel *model in modelArray){
        if(model.clipPath && model.clipType != NvClipNone){
            //clip is a images
            NvsVideoClip *videoClip = nil;
            if(model.clipType == NvClipVideo) {//视频
                //has no trim in and trim out
                if(model.triminTimeStamp.longLongValue == 0 && model.trimoutTimeStamp.longLongValue == 0) {
                    videoClip = [videoTrack appendClip:model.clipPath];
                } else {
                    videoClip = [videoTrack appendClip:model.clipPath trimIn:model.triminTimeStamp.longLongValue trimOut:model.trimoutTimeStamp.longLongValue];
                }
            } else {//图片
                if(model.imageDuration.intValue == 0) {
                    videoClip = [videoTrack appendClip:model.clipPath];
                } else {
                    videoClip = [videoTrack appendClip:model.clipPath trimIn:0 trimOut:model.imageDuration.intValue * NS_TIME_BASE];
                }
            }
            if(model.audioVolumn.floatValue != -1) {
                [videoClip setVolumeGain:model.audioVolumn.floatValue rightVolumeGain:model.audioVolumn.floatValue];
            }
            
            if(model.clipCaption.length != 0) {
                [self.timeline addCaption:model.clipCaption inPoint:videoClip.inPoint duration:videoClip.outPoint - videoClip.inPoint captionStylePackageId:nil];
            }
        }
    }
    [videoTrack setVolumeGain:model.audioVolumn.floatValue rightVolumeGain:model.audioVolumn.floatValue];
    //  安装主题
    if(model.themeUuid && ![self.timeline getCurrentThemeId]) {
        [self.timeline applyTheme:model.themeUuid];
    }
    //  安装贴纸
    //remove current sticker
    NvsTimelineAnimatedSticker *sticker = [self.timeline getFirstAnimatedSticker];
    if(sticker != nil) {
        [self.timeline removeAnimatedSticker:sticker];
    }
    //none sticker
    if(model.stickerPackageId == nil || [model.stickerPackageId isEqualToString:@""]) {
        //do nothing
    } else {
        [self.timeline addAnimatedSticker:0 duration:self.timeline.duration animatedStickerPackageId:model.stickerPackageId];
    }
    //  安装背景音乐
    NSLog(@"audio track count: %d", self.timeline.audioTrackCount);
    if(self.timeline.audioTrackCount) {
        [self.timeline removeAudioTrack:0];
    }
    
    float bgMusicLengthInSeconds = (model.bgMusicTrimOut.floatValue - model.bgMusicTrimIn.floatValue);
    if(model.bgMusicPath != nil && bgMusicLengthInSeconds > 0) {
        NvsAudioTrack *bgMusicTrack = [self.timeline appendAudioTrack];
        int64_t timelineDuration = self.timeline.duration;
        int64_t bgMusicLength = bgMusicLengthInSeconds * NS_TIME_BASE;
        int64_t remainDuration = timelineDuration;
        while (remainDuration > bgMusicLength) {
            [bgMusicTrack appendClip:model.bgMusicPath trimIn:model.bgMusicTrimIn.floatValue * NS_TIME_BASE trimOut:model.bgMusicTrimOut.floatValue * NS_TIME_BASE];
            remainDuration -= bgMusicLength;
        }
        [bgMusicTrack appendClip:model.bgMusicPath trimIn:model.bgMusicTrimIn.floatValue * NS_TIME_BASE trimOut:model.bgMusicTrimIn.floatValue * NS_TIME_BASE + remainDuration];
        [bgMusicTrack setVolumeGain:model.soundVolumn.floatValue rightVolumeGain:model.soundVolumn.floatValue];
        [self.timeline setThemeMusicVolumeGain:0 rightVolumeGain:0];
    } else {
        [self.timeline setThemeMusicVolumeGain:model.soundVolumn.floatValue rightVolumeGain:model.soundVolumn.floatValue];
    }
    
    self.playStart = 0;
    self.playEnd = self.timeline.duration;
    [self updateTotalLabel];
    [self startSeekTimeline:self.playStart isLeft:YES];
    triminTimeStamp = 0;
    trimoutTimeStamp = self.timeline.duration;
}

- (void)startSeekTimeline:(float)timestamp isLeft:(BOOL)isLeft{
    [self pause];
    [self.streamingContext seekTimeline:self.timeline timestamp:timestamp videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
    if (isLeft) {
        triminTimeStamp = timestamp;
        self.currentTimeLabel.text = [Utils stringWithTime:1.0*timestamp/NS_TIME_BASE];
        [self.slider setValue:1.0*timestamp/self.timeline.duration animated:YES];
    } else {
        trimoutTimeStamp = timestamp;
    }
    
}
//设置出入点并将视频初始画面设为开始点
- (void)setTrimIn:(int64_t)trimIn trimOut:(int64_t)trimOut {
    triminTimeStamp = trimIn;
    trimoutTimeStamp = trimOut;
    [self startSeekTimeline:triminTimeStamp isLeft:YES];
}

- (int64_t)duration {
    return self.playEnd - self.playStart;
}

//获取当前时间点
- (int64_t)currentTimeLine {
    return [self.streamingContext getTimelineCurrentPosition:self.timeline];
}

//播放进度的回调每秒10次
- (void)handleSliderChange {
    int64_t millisecond = [self currentTimeLine];
    self.currentTimeLabel.text = [Utils stringWithTime:(millisecond - self.playStart) / NS_TIME_BASE];

    [self.slider setValue:(1.0* (millisecond - self.playStart) / (self.playEnd - self.playStart)) animated:YES];
    
    if ([self.delegate respondsToSelector:@selector(nvWindowPlayer:currentTimeString:totalTimeString:)]) {
        [self.delegate nvWindowPlayer:self currentTimeString:self.currentTimeLabel.text totalTimeString:self.totalTimeLabel.text];
    }
}
//播放按钮被点击
- (IBAction)playButtonClick:(UIButton *)sender {
    if (isPlaying) {//停止播放
        [self pause];
        
    } else {//开始播放
        [self play];
    }
}
//拖动进度条
- (IBAction)valueChange:(id)sender {
    [self pause];
    int64_t seekTime = self.playStart + _slider.value * (self.playEnd - self.playStart);
    [self.streamingContext seekTimeline:self.timeline timestamp:seekTime videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
    int64_t millisecond = [self currentTimeLine];
    self.currentTimeLabel.text = [Utils stringWithTime:(millisecond - self.playStart) / NS_TIME_BASE];
   
    if ([self.delegate respondsToSelector:@selector(nvWindowPlayer:currentTimeString:totalTimeString:)]) {
        [self.delegate nvWindowPlayer:self currentTimeString:self.currentTimeLabel.text totalTimeString:self.totalTimeLabel.text];
    }
}

//MARK:delegate
//播放结束
- (void)didPlaybackEOF:(NvsTimeline *)timeline {
    if (triminTimeStamp!=0||trimoutTimeStamp!=self.timeline.duration) {
        [self.streamingContext seekTimeline:self.timeline timestamp:triminTimeStamp videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
        self.slider.value = 1.0*triminTimeStamp/self.timeline.duration;
        self.currentTimeLabel.text = [Utils stringWithTime:1.0*triminTimeStamp/NS_TIME_BASE];

    } else {
        [self.streamingContext seekTimeline:self.timeline timestamp:self.playStart videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
        self.slider.value = 0;
        self.currentTimeLabel.text = @"00:00";
    }
    [self pause];
}
//播放停止
- (void)didPlaybackStopped:(NvsTimeline *)timeline {
}

- (void)clear {
    [timer invalidate];
    self.streamingContext.delegate = nil;
    [self.streamingContext stop];
    [self.streamingContext connectTimeline:self.timeline withLiveWindow:nil];
    if(_needClearTimeLine) {
        [self.streamingContext removeTimeline:self.timeline];
    }
}
//播放器销毁
-(void)dealloc {
    NSLog(@"播放器释放了");
}

@end
